package session.stateless;

import entity.SaleInquiry;
import entity.SaleLead;
import entity.SaleLead.CustomerType;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class SaleLeadBean implements SaleLeadBeanLocal {
    @PersistenceContext(unitName = "M10-IS3102-ejbPU")
    EntityManager em;
    
    public SaleLeadBean(){}
    
    //Method B.1.1.1
    public long createSaleLead(String name, String NRIC, String email, String address, String contactNumber, CustomerType customerType) {
        SaleLead saleLead = new SaleLead();
        saleLead.setSaleLeadName(name);
        saleLead.setSaleLeadNRIC(NRIC);
        saleLead.setSaleLeadEmail(email);
        saleLead.setSaleLeadAddress(address);
        saleLead.setSaleLeadContactNumber(contactNumber);
        saleLead.setCustomerType(customerType);
        List<SaleInquiry> saleInquiries = new ArrayList<SaleInquiry>();
        saleLead.setSaleInquiries(saleInquiries);
        em.persist(saleLead);        
        
        return saleLead.getSaleLeadId();
    }
   
    //Method B.1.1.2
    public void updateSaleLead(long saleLeadId, String saleLeadName, String saleLeadNRIC, String saleLeadEmail, String saleLeadAddress, String saleLeadContactNumber, CustomerType customerType) 
    {
        SaleLead saleLead = em.find(SaleLead.class, saleLeadId);       
        if (saleLead ==null)
             System.out.println("Sale Lead does not exist. Please try again.");
        else
        {
            saleLead.setSaleLeadName(saleLeadName);
            saleLead.setSaleLeadNRIC(saleLeadNRIC);
            saleLead.setSaleLeadEmail(saleLeadEmail);
            saleLead.setSaleLeadAddress(saleLeadAddress);
            saleLead.setSaleLeadContactNumber(saleLeadContactNumber);
            em.flush();
        }
    }
    
    //Method B.1.1.3
    public void deleteSaleLead(long saleLeadId) {
        SaleLead saleLead = em.find(SaleLead.class, saleLeadId);
        if (saleLead==null) 
            System.out.println("Hi!");
            //throw new ExistException("Sale Lead does not exist.");
        else
        {
            //Remove all dependencies before deleting
            em.remove(saleLead);
        }
    }
    
    //Method B.1.1.4
    public List<SaleLead> getSalesLead() {
        Query q = em.createQuery("SELECT c FROM SaleLead c");
                      
        return q.getResultList();        
    }
    
    @Remove
    public void remove() {
       System.out.println("SaleLeadBean:remove()");               
    }

    public SaleLead find(long saleLeadId) {
        return em.find(SaleLead.class, saleLeadId);
    }
}
